<template>
    <div class="select-application">
        <div class="search">
            <el-input :placeholder="$t('common.base.search')" v-model="searchValue" clearable
                prefix-icon="el-icon-search">
            </el-input>
        </div>
        <!-- 选择应用 -->
        <div class="select-application-content" v-show="!showApi" v-loading="loading">
            <el-menu mode="horizontal" class="sign-title" :default-active="selectedTab" @select="menuSelect">
                <el-menu-item key="system" index="system">内部应用</el-menu-item>
                <el-menu-item key="third" index="third" v-if="appList.thirdAppList">第三方应用</el-menu-item>
            </el-menu>
            <div class="title">
                选择应用
            </div>
            <div class="content">
                <div 
                    v-for="item in selectedTab === 'system' ? appList.systemAppList : appList.thirdAppList"
                    :key="item.appId" 
                    class="item" 
                    :class="{ 'active' : item.appId == state.currentNodeInfoFront.options.appId }"
                    @click="clickApp(item)" 
                    v-show="fuzzyMatching(searchValue, item.name)"
                >
                    <!-- 内部应用图标 -->
                    <i v-if="selectedTab == 'system'" class="iconfont" :class="item.logo"></i>
                    <!-- 第三方应用图标 -->
                    <img v-else-if="item.logo" :src="item.logo" class="iconfont" />
                    <div v-else class="iconfont">
                        <i>{{ item.name.substring(0, 2)}}</i>
                    </div>
                    <div class="app-name" :data-fulltext="item.name">{{ item.name }}</div>
                </div>
                <div v-if="selectedTab !== 'system'" class="tip">
                    <span class="mar-r-8">更多应用，可在集成中心配置</span>
                    <el-button type="text" @click="openIntegration">点击跳转</el-button>
                </div>
            </div>
        </div>
        <!-- 选择对象 -->
        <div class="select-object-content" v-if="showApi" v-loading="loading">
            <div class="title">
                <span class="title-app-kind" @click="$emit('changeShowApi', false)">
                    {{ selectedTab == 'system' ? '内部应用' : '第三方应用'}}
                </span>
                <span class="title-icon"><i class="iconfont icon-right"></i></span>
                <span class="title-app-name">{{ state.currentNodeInfoFront.options.appName }}</span>
            </div>
            <div class="select-kind" v-if="showModule">
                <div class="select-kind-title">
                    {{ openModuleObj.moduleTitle }}
                </div>
                <el-select v-model="moduleId" placeholder="请选择" style="width: 100%;" filterable>
                    <el-option v-for="item in openModuleObj.moduleList" :key="item.moduleId" :label="item.name"
                        :value="item.moduleId">
                    </el-option>
                </el-select>
            </div>
            <div class="select-object" v-if="showModule && moduleId">
                <div class="select-object-title">
                    选择对象
                </div>
                <div class="select-object-content">
                    <div 
                        class="select-object-item"
                        :class="{ 'active' : i.apiId === state.currentNodeInfoFront.options.apiId }"
                        v-for="i in ((openModuleObj.moduleList || []).find(i => i.moduleId == moduleId) || {selectObjList: []}).selectObjList"
                        @click="clickObject(i)" 
                        v-show="fuzzyMatching(searchValue, i.name)" 
                        :key="i.apiId"
                    >
                        <div class="object-name">{{ i.name }}</div>
                        <div class="object-info">{{ i.desc }}</div>
                    </div>
                    <!-- 附加组件 -->
                    <div class="add-ons" v-if="additionalList && additionalList.length">
                        <div class="add-ons-title">
                            附加组件
                        </div>
                        <div 
                            class="add-ons-item" 
                            :class="{ 'active' : i.apiId === state.currentNodeInfoFront.options.apiId }"
                            v-for="i in (additionalList || [])" 
                            @click="clickObject(i)" 
                            v-show="fuzzyMatching(searchValue, i.name)" 
                            :key="i.apiId"
                        >
                            <div class="add-ons-name">{{ i.name }}</div>
                            <div class="add-ons-info">{{ i.desc }}</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="select-object" v-else-if="!showModule && closeModuleObj">
                <div class="select-object-title">
                    选择对象
                </div>
                <div class="select-object-content">
                    <div 
                        class="select-object-item" 
                        v-for="i in (closeModuleObj.selectObjList || [])"
                        :class="{ 'active' : i.apiId === state.currentNodeInfoFront.options.apiId }"
                        @click="clickObject(i)" 
                        v-show="fuzzyMatching(searchValue, i.name)" 
                        :key="i.apiId"
                    >
                        <div class="object-name">{{ i.name }}</div>
                        <div class="object-info">{{ i.desc }}</div>
                    </div>
                    <!-- 附加组件 -->
                    <div class="add-ons" v-if="additionalList && additionalList.length">
                        <div class="add-ons-title">
                            附加组件
                        </div>
                        <div 
                            class="add-ons-item" 
                            :class="{ 'active' : i.apiId === state.currentNodeInfoFront.options.apiId }"
                            v-for="i in (additionalList || [])" 
                            @click="clickObject(i)" 
                            v-show="fuzzyMatching(searchValue, i.name)" 
                            :key="i.apiId"
                        >
                            <div class="add-ons-name">{{ i.name }}</div>
                            <div class="add-ons-info">{{ i.desc }}</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { getAppList, getApiList } from '@src/modules/trigger/api/trigger.js'
import state from '@src/modules/trigger/view/setting/util/state.js'

export default {
    name: 'SelectApplication',
    props: {
        showApi: {
            type: Boolean,
            default: false,
        },
    },
    computed: {
        state() {
            return state;
        },
        additionalList() {
            if (this.showModule) {
                if (state.currentNodeInfoFront.options?.moduleId) {
                    return (this.openModuleObj.moduleList || []).find(i => i.moduleId == this.moduleId)?.additionalList;
                }
            }
            return this.closeModuleObj?.additionalList || [];
        },
    },
    async created() {
        this.fetchApiList()
    },
    watch: {
        showApi(val) {
            if (val) {
                this.getApi();
            }
        },
    },
    data() {
        return {
            selectedTab: 'system', // 选中的应用类型 内部应用/第三方应用
            searchValue: '', // 搜索框的值
            appList: { // 应用类型的数据
                systemAppList: null, // 内部应用数据
                thirdAppList: null, // 第三方应用数据
            },
            showModule: false, // 是否显示选择类型
            openModuleObj: { // 显示选择类型时的的对象
                moduleTitle: '', // 类型标题
                moduleList: null, // 类型列表
            },
            closeModuleObj: {}, // 不显示选择类型时的的对象
            moduleId: '', // 类型的id
            showSelectApi: false, // 是否显示选择api
            loading: false,
        };
    },
    methods: {
        async fetchApiList() {
            try {
                this.loading = true;
                const { status = 1, data = {}, message = '' } = await getAppList({
                    way: state.executeWay.way,
                });
                if (status === 0) {
                    this.appList = data;
                    if (state.currentNodeInfoFront?.options?.appId) {
                        this.$emit('changeShowApi', true);
                        // this.getApi();
                    }
                    this.moduleId = state.currentNodeInfoFront.options?.moduleId;
                } else {
                    this.$message.error(message);
                }
            } catch (error) {
                console.log(error);
            } finally {
                this.loading = false;
            }
        },
        // 切换内部应用/第三方应用
        menuSelect(key) {
            this.selectedTab = key;
            this.searchValue = '';
        },
        // 选择应用
        clickApp(item) {
            if (state.currentNodeInfoFront.options?.appId === item.appId) {
                this.$emit('changeShowApi', true);
                this.moduleId = state.currentNodeInfoFront.options?.moduleId;
                return;
            }
            const changeApp = () => {
                this.searchValue = '';
                this.$set(state.currentNodeInfoFront, 'options', {
                    appId: item.appId,
                    appName: item.name,
                    appLogo: item.logo,
                });
                state.currentNodeInfoFront.options.moduleId = null;
                state.currentTriggerInfo.eventWayInfo = [];
                state.executeWay.options = {};
                this.moduleId = null;
                this.$emit('changeShowApi', true);
            }
            
            if (state.currentNodeInfoFront.options?.appId && state.currentNodeInfoFront.options?.appId !== item.appId) {
                this.$confirm('此操作将会删除后续节点, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    changeApp();
                }).catch(() => {});
            } else {
                changeApp();
            }
        },
        // 选择api
        clickObject(item) {
            if (state.currentNodeInfoFront.options?.apiId === item.apiId) {
                this.$emit('clickApi');
                return;
            }
            const changeApi = () => {
                this.$set(state.currentNodeInfoFront, 'options', {
                    appId: state.currentNodeInfoFront.options.appId,
                    appName: state.currentNodeInfoFront.options.appName,
                    appLogo: state.currentNodeInfoFront.options.appLogo,
                    moduleId: this.moduleId,
                    apiId: item.apiId,
                    selectObjName: item.name,
                })
                state.currentTriggerInfo.eventWayInfo = [];
                state.executeWay.options = {};
                this.$emit('clickApi');
            }
            if (state.currentNodeInfoFront.options?.apiId && state.currentNodeInfoFront.options?.apiId !== item.apiId) {
                this.$confirm('此操作将会删除后续节点, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    changeApi();
                }).catch(() => {});
            } else {
                changeApi();
            }
        },
        openIntegration() {
            this.$platform.openTab({
                title: '集成中心',
                url: '/foundation/setting/develop/systemCenter',
            })
        },
        getApi() {
            this.loading = true;
            this.searchValue = '';
            getApiList({
                appId: state.currentNodeInfoFront.options.appId,
                direction: 'from',
            }).then(res => {
                if (res.status == 0) {
                    const data = res.data;
                    this.showModule = data?.showModule ?? false;
                    if (this.showModule) {
                        this.openModuleObj = data?.openModuleObj;
                    } else {
                        this.closeModuleObj = data?.closeModuleObj;
                    }
                } else {
                    this.$message.error(res?.message);
                }
            }).catch(e => {
                console.log(e);
            }).finally(() => {
                this.loading = false;
            })
        },
        fuzzyMatching(target, item) {
            if (target.length > item.length) return false;
            let i = 0, j = 0;
            for (;j < item.length; j++) {
                if (target[i] === item[j]) {
                    i++;
                    if (i === target.length) {
                        return true;
                    }
                }
            }
            return !target;
        },
    }
};
</script>

<style lang="scss" scoped>
.active {
    border: 1px solid var(--color-primary-light-6) !important;
}
::v-deep .el-steps--simple {
    padding: 24px !important;
}
.select-application {
    height: calc(100% - 72px);
    overflow: hidden;
    padding: 16px 24px;

    ::v-deep .el-menu {
        margin-top: 16px;

        .el-menu-item {
            height: 40px;
            line-height: 40px;
        }
    }

    .select-application-content {
        height: calc(100% - 56px);
        .title {
            font-size: 14px;
            margin: 16px 0;
        }

        .content {
            max-height: calc(100% - 70px);
            overflow: auto;
            display: flex;
            flex-wrap: wrap;
            align-items: flex-start;

            .item {
                width: 164px;
                height: 64px;
                display: flex;
                align-items: center;
                margin-bottom: 20px;
                border-radius: 4px;
                border: 1px solid #E4E7ED;
                padding: 0 16px;
                position: relative;
                margin-right: 16px;
                cursor: pointer;

                .iconfont {
                    width: 32px;
                    min-width: 32px;
                    height: 32px;
                    border-radius: 8px;
                    font-size: 18px;
                    background: var(--color-primary-light-1);
                    color: var(--color-primary-light-6);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin-right: 8px;
                    i {
                        font-size: 12px;
                        font-style: normal;
                    }
                }

                .app-name {
                    overflow:hidden;
                    word-wrap: break-word;
                    text-overflow:ellipsis;
                    display:-webkit-box;
                    -webkit-box-orient:vertical;
                    -webkit-line-clamp:2;  
                }
            }
            .tip {
                width: 100%;
            }
            .item:hover {
                border-color: var(--color-primary-light-6);
            }
        }
    }

    .select-object-content {
        height: calc(100% - 30px);
        display: flex;
        flex-direction: column;
        overflow: auto;
        .title {
            margin-top: 16px;
            height: 40px;
            line-height: 40px;
            font-size: 14px;
            border-bottom: 1px solid #E4E7ED;

            &-app-kind {
                margin-right: 8px;
                cursor: pointer;
            }

            &-icon {
                margin-right: 8px;
            }
        }

        .select-kind {
            margin-top: 16px;

            &-title {
                font-size: 14px;
                margin-bottom: 8px;
            }
        }

        .select-object {
            flex: 1;
            height: calc(100% - 148px);
		    width: 100%;
		    margin-top: 16px;

            &-title {
                font-size: 14px;
                margin-bottom: 8px;
            }

            &-content {
                height: calc(100% - 28px);
                overflow: auto;
            }

            &-item {
                margin-bottom: 16px;
                border: 1px solid #E4E7ED;
                border-radius: 4px;
                padding: 8px 16px;
                cursor: pointer;

                .object-name {
                    font-size: 14px;
                    margin-bottom: 2px;
                    height: 22px;
                    line-height: 22px;
                    font-weight: 500;
                }

                .object-info {
                    font-size: 12px;
                    height: 20px;
                    line-height: 20px;
                    color: #595959;
                }
            }

            &-item:hover {
                border-color: var(--color-primary-light-6);
            }
        }

        .add-ons {
            margin-top: 16px;

            &-title {
                height: 36px;
                background-color: #F5F8FA;
                border-left: 3px solid var(--color-primary-light-6);
                padding: 8px 12px;
                margin-bottom: 16px;
                font-size: 12px;
                font-weight: 500;
            }

            &-item {
                margin-bottom: 16px;
                border: 1px solid #E4E7ED;
                border-radius: 4px;
                padding: 8px 16px;
                cursor: pointer;

                .add-ons-name {
                    font-size: 14px;
                    margin-bottom: 2px;
                    height: 22px;
                    line-height: 22px;
                    font-weight: 500;
                }

                .add-ons-info {
                    font-size: 12px;
                    height: 20px;
                    line-height: 20px;
                    color: #595959;
                }
            }

            &-item:hover {
                border-color: var(--color-primary-light-6);
            }
        }
    }
}
</style>